# -*- coding : "utf-8" -*-
# @姓名       : GUI
# @日期       : 2023/2/12 19:58
# @FileName  ： exchange.py
# @Software  ： PyCharm
import copy
import json.decoder
import logging
import re
import allure
import jsonpath
from commons.files import YamlFile
from commons.models import CaseInfo
from commons.templates import Template

logger = logging.getLogger(__name__)


class Exchange:
    def __init__(self, path):
        self.file = YamlFile(path)

    @allure.step("提取变量")
    def extract(self, resp, var_name, attr, expr: str, index: int):
        # resp中 json是方法，不是属性，需要手动改为属性
        resp = copy.deepcopy(resp)
        try:
            resp.json = resp.json()
        except json.decoder.JSONDecodeError:
            resp.json = {"msg": " is not json data"}
        data = getattr(resp, attr)

        if expr.startswith("/"):  # 是 xpath
            res = None
        elif expr.startswith("$"):  # 是jsonpath
            data = dict(data)  # 强转字典
            res = jsonpath.jsonpath(data, expr)
            # print(f"{res=}")
        else:  # 是正则
            res = re.findall(expr, str(data))
        print(f"{res=}")
        if res:  # 如果有数据
            value = res[index]
        else:  # 如果没有数据
            value = "not data"

        logger.debug(f"{var_name} = {value}")

        self.file[var_name] = value  # 保存变量
        self.file.save()  # 持久化存储到文件

    @allure.step("替换变量")
    def replace(self, case_info: CaseInfo):
        # 1. 将case_info 转成字符串
        case_info_str = case_info.to_yaml()
        # 2. 替换字符串
        case_info_str = Template(case_info_str).render(self.file)
        # 3. 将字符串 转成case_info
        new_case_info = case_info.by_yaml(case_info_str)
        return new_case_info

